<template>
  <el-dialog
    title="更新故事"
    :visible.sync="visible"
    width="50%"
    append-to-body
  >
    <avue-form
      ref="crud"
      v-model="form"
      :option="storyOption"
    ></avue-form>
    <div class="flex-end">
      <el-button @click="visible = false">取消</el-button>
      <el-button
        class="btn"
        :loading="loading"
        type="primary"
        @click="confirm"
      >
        确定
      </el-button>
    </div>
  </el-dialog>
</template>
<script>
import { storyOption } from '@/const/crud/pet/base-file';
import { updateStory, getShelfRecord } from '@/api/core/pet-file';
export default {
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String,
    },
  },
  data() {
    return {
      storyOption: storyOption(),
      form: {},
      loading: false,
    };
  },
  computed: {
    visible: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      },
    },
  },
  watch: {
    visible(val) {
      if (!val) {
        this.$refs.crud.resetFields();
      } else {
        this.getShelfRecord();
      }
    },
  },
  methods: {
    async getShelfRecord() {
      const res = await getShelfRecord(this.id);
      if (res.data.data && res.data.data.introduction) {
        this.form.introduction = res.data.data.introduction;
      }
    },
    confirm() {
      this.$refs.crud.validate(async (valid, done) => {
        if (valid) {
          this.loading = true;
          try {
            const params = {
              id: this.id,
              introduction: this.form.introduction,
            };
            await updateStory(params);
            this.$message.success('更新故事成功');
            this.$emit('success');
            done();
            this.loading = false;
            this.visible = false;
          } catch (error) {
            done();
            this.loading = false;
            throw new Error(error);
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped></style>
